package com.tool.sqlexecutor.command;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tool.sqlexecutor.config.Config;
import com.tool.sqlexecutor.config.ConfigCache;
import org.apache.commons.jxpath.JXPathContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

@ShellComponent
public class ConfigCommands {
    Logger logger = LoggerFactory.getLogger(ConfigCommands.class);

    private Gson gson;

    public ConfigCommands() {
        this.gson = new GsonBuilder().setPrettyPrinting().create();
    }

    @ShellMethod(value = "配置数据源,默认加载config.json")
    public String reset(@ShellOption(value = {"--file", "-f"}, defaultValue = "config.json") File file) {
        logger.info("absolutePath:" + file.getAbsolutePath());
        if (!file.exists()) {
            return "Please check the file path and try again.!File - " + file.getAbsolutePath();
        }
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            Config config = new Gson().fromJson(reader, Config.class);
            ConfigCache.INSTANCE.setConfig(config);
            logger.info("load config success");
            return "load config success!env：\n" + gson.toJson(config.getServer().keySet());
        } catch (Exception e) {
            e.printStackTrace();
            return "Failure to refresh configuration!";
        }
    }

    @ShellMethod(value = "查看配置信息")
    public String config(@ShellOption(help = "xpath,指定要查看的属性;如果不指定则显示全部", value = {"--key", "-k"}, defaultValue = "") String key) {
        if (ConfigCache.INSTANCE.getConfig() == null) {
            return "请先指定配置:reset [file]";
        }
        if (StringUtils.isEmpty(key)) {
            return gson.toJson(ConfigCache.INSTANCE.getConfig());
        } else {
            Object value = JXPathContext.newContext(ConfigCache.INSTANCE.getConfig()).getValue("server/" + key);
            return gson.toJson(value);
        }
    }
}